package com.itguigu.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itguigu.model.process.ProcessTemplate;
import com.itguigu.model.process.ProcessType;
import com.itguigu.process.mapper.ProcessTemplateMapper;
import com.itguigu.process.mapper.ProcessTypeMapper;
import com.itguigu.process.service.ProcessService;
import com.itguigu.process.service.ProcessTemplateService;
import com.itguigu.process.service.ProcessTypeService;
import com.itguigu.wechat.service.MessageService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 */
@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper , ProcessTemplate> implements ProcessTemplateService {

    @Resource
    private MessageService messageService;

    @Resource
    private ProcessTemplateMapper processTemplateMapper;

    @Resource
    private ProcessTypeService processTypeService;

    @Resource
    private ProcessService processService;
    @Override
    public IPage<ProcessTemplate> selectPageProcessTemplate(Page<ProcessTemplate> pageParam) {
        // 调用mapper的方法 实现分页查询
        Page<ProcessTemplate> processTemplatePage = processTemplateMapper.selectPage(pageParam , null);
        // 查询返回分页数据 , 从分页数据中获取列表list集合
        List<ProcessTemplate> processTemplateList = processTemplatePage.getRecords();

        // 遍历list集合 , 得到每个对象的审批类型id
        for (ProcessTemplate processTemplate : processTemplateList) {
            Long processTypeId = processTemplate.getProcessTypeId();
            // 根据审批类型id , 查询对应名称
            ProcessType processType = processTypeService.getById(processTypeId);
            if (processType == null) {
                continue;
            }
            processTemplate.setProcessTypeName(processType.getName());
        }
        // 完成最终封装processTypename
        return processTemplatePage;
    }

    @Override
    public void publish(Long id) {
        // 修改模板发布状态 1 : 已经发布
        ProcessTemplate processTemplate = baseMapper.selectById(id);
        processTemplate.setStatus(1);
        baseMapper.updateById(processTemplate);

        // TODO 部署审批模板

        // 优先发步在线流程设计
        if (StringUtils.hasText(processTemplate.getProcessDefinitionPath())) {
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }
    }
}
